package game.editer;

import game.worlds.GameEffect;
import hx.display.DisplayObject;
import hx.layout.AnchorLayoutData;
import hx.layout.AnchorLayout;
import hx.display.Quad;
import hx.display.Box;

/**
 * 边界选择器
 */
class ObjectSelectEditer extends Box {
	/**
	 * 移动工具
	 */
	public var tools:Array<ObjectSelectTools> = [];

	private var __currentEditTools:ObjectSelectTools;

	public var currentEditTools(get, set):ObjectSelectTools;

	private function get_currentEditTools():ObjectSelectTools {
		return this.__currentEditTools;
	}

	private function set_currentEditTools(value:ObjectSelectTools):ObjectSelectTools {
		this.__currentEditTools = value;
		for (t in tools) {
			if (t == value) {
				t.visible = true;
			} else {
				t.visible = false;
			}
		}
		return value;
	}

	override function onInit() {
		super.onInit();
		this.layout = new AnchorLayout();

		var color = 0xffff00;
		var alpha = 0.8;

		var quad = new Quad(1, 1, color);
		quad.layoutData = new AnchorLayoutData(0, null, 0, null);
		quad.alpha = alpha;
		quad.mouseEnabled = false;
		this.addChild(quad);

		var quad = new Quad(1, 1, color);
		quad.layoutData = new AnchorLayoutData(0, 0, null, 0);
		quad.alpha = alpha;
		quad.mouseEnabled = false;
		this.addChild(quad);

		var quad = new Quad(1, 1, color);
		quad.layoutData = new AnchorLayoutData(null, 0, 0, 0);
		quad.alpha = alpha;
		quad.mouseEnabled = false;
		this.addChild(quad);

		var quad = new Quad(1, 1, color);
		quad.layoutData = new AnchorLayoutData(0, 0, 0, null);
		quad.alpha = alpha;
		quad.mouseEnabled = false;
		this.addChild(quad);

		var moveTools = new ArrowMoveTools();
		moveTools.width = moveTools.height = 1;
		this.addChild(moveTools);
		moveTools.layoutData = AnchorLayoutData.center();
		tools.push(moveTools);

		currentEditTools = moveTools;
		
		this.visible = false;
	}

	public function update():Void {
		if (selectedDisplay != null) {
			if (selectedDisplay.parent == null) {
				// 那么尝试找到对应的特效对象
				if (selectedDisplay is GameEffect) {
					for (object in EditerStage.world.displayBox.children) {
						if (object is GameEffect) {
							var effect = cast(object, GameEffect);
							#if editer
							if (effect.originData == cast(selectedDisplay, GameEffect).originData) {
								selectedDisplay = effect;
							}
							#end
						}
					}
				}
				if (selectedDisplay.parent == null) {
					selectedDisplay = null;
				}
			}
			if (selectedDisplay != null) {
				var bounds = selectedDisplay.getBounds(selectedDisplay.parent);
				this.width = bounds.width;
				this.height = bounds.height;
				this.x = bounds.x;
				this.y = bounds.y;
				this.visible = true;
			} else {
				this.visible = false;
			}
		} else {
			this.visible = false;
		}
	}

	/**
	 * 当前已选择的显示对象
	 */
	public var selectedDisplay(default, set):DisplayObject;

	private function set_selectedDisplay(value:DisplayObject):DisplayObject {
		this.selectedDisplay = value;
		return value;
	}
}
